package msg

import (
	"context"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	uuid "github.com/satori/go.uuid"
	"go-zero-project/services/user/api/constans"
	"go-zero-project/services/user/api/internal/initialize/mq/producer"

	"go-zero-project/services/user/api/internal/svc"
	"go-zero-project/services/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type TransMsgLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewTransMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TransMsgLogic {
	return &TransMsgLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TransMsgLogic) TransMsg(req *types.SendTransMsgReq) (resp *types.SendTransMsgResp, err error) {
	// covert request
	bodyByte := []byte(req.Msg)
	message := primitive.Message{Topic: constans.UserTransTopic, Body: bodyByte}
	message.WithTag("trans")
	message.WithKeys([]string{uuid.NewV4().String()})
	// send msg
	newMqTransBO := producer.NewMqTransBO(constans.UserTransTopic, &message, localTransFun, checkLocalFun)
	sendErr := newMqTransBO.SendTransMsg(l.ctx, l.svcCtx.TransProducer)
	if sendErr != nil {
		return nil, sendErr
	}
	// return obj
	return &types.SendTransMsgResp{
		Topic: constans.UserTransTopic,
		Tag:   "trans",
		Msg:   string(bodyByte),
	}, nil
}

func localTransFun(msg *primitive.Message) primitive.LocalTransactionState {
	logx.Infof("TransMsgLogic#NewTransMsgLogic 执行本地事务>..")
	//return primitive.CommitMessageState
	// 模拟回查
	return primitive.UnknowState
}
func checkLocalFun(msg *primitive.MessageExt) primitive.LocalTransactionState {
	logx.Infof("TransMsgLogic#checkLocalFun 执行事务回查>..")
	return primitive.CommitMessageState
}
